package com.yunc.modules.sys.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.utils.BaseConstant;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysUser;
import com.yunc.modules.sys.entity.SysUserDept;
import com.yunc.modules.sys.entity.SysUserRole;
import com.yunc.modules.sys.mapper.SysUserMapper;
import com.yunc.modules.sys.service.ISysUserDeptService;
import com.yunc.modules.sys.service.ISysUserRoleService;
import com.yunc.modules.sys.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户信息
 *
 * @author taocongcong
 * @create 2017-12-15 13:46
 */
@Service("sysUserService")
@CacheConfig(cacheNames = "sysUser")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper,SysUser> implements ISysUserService {

    private final SysUserMapper sysUserMapper;
    private final ISysUserRoleService sysUserRoleService;
    private final ISysUserDeptService sysUserDeptService;

    @Override
    public List<String> queryMenuIdByUserId(String userId) {
        return sysUserMapper.queryMenuIdByUserId(userId);
    }

    @Override
    public Set<String> queryUserMenuPermsSet(String userId) {
        List<String> permsList = sysUserMapper.queryUserMenuPermsList(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : permsList) {
            if (StringUtils.isNotEmpty(perm)){
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<String> queryUserMenuPermsList(String userId) {
        List<String> permsList = sysUserMapper.queryUserMenuPermsList(userId);
        return permsList;
    }

    @Override
    public List<String> queryMenuIdByRoleId(String roleId) {
        return sysUserMapper.queryMenuIdByRoleId(roleId);
    }

    @Override
    public IPage<SysUser> pageInfo(Page<SysUser> page, SysUser sysUser) {
        // 分页
        return sysUserMapper.pageInfo(page, sysUser.getUserName(), sysUser.getDeptCode());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R saveUser(SysUser user) {
        // 设置默认密码
        String password = DigestUtil.md5Hex(BaseConstant.DEFAULT_PASSWORD);
        user.setUserPassword(password);
        user.setRemoveTag(BaseConstant.REMOVE_N);
        user.setCreateTime(new Date());
        boolean flag = this.save(user);
        if (!flag) {
            return R.error();
        }
        // 修改权限
        boolean userRoleFlag = sysUserRoleService.insertList(user.getId(), user.getRoleIds());
        if (!userRoleFlag) {
            return R.error();
        }
        // 修改部门
        boolean userDeptFlag = sysUserDeptService.insertList(user.getId(), user.getDeptIds());
        if (!userDeptFlag) {
            return R.error();
        }
        return R.ok();
    }

    @Override
    public SysUser getByLoginName(String loginName) {
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(loginName);
        List<SysUser> sysUserList = this.list(new QueryWrapper<>(sysUser));
        if (sysUserList != null && sysUserList.size() > 0) {
            return sysUserList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public R updateUser(SysUser user) {
        String userId = user.getId();
        boolean flag = this.updateById(user);
        if (!flag) {
            return R.error();
        }
        // 删除权限
        SysUserRole record = new SysUserRole();
        record.setUserId(userId);
        boolean removeFlag = sysUserRoleService.remove(new QueryWrapper<>(record));
        boolean userRoleFlag = sysUserRoleService.insertList(userId, user.getRoleIds());
        if (!removeFlag || !userRoleFlag) {
            return R.error();
        }
        // 修改部门
        QueryWrapper<SysUserDept> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        sysUserDeptService.remove(qw);
        boolean userDeptFlag = sysUserDeptService.insertList(user.getId(), user.getDeptIds());
        if (!userDeptFlag) {
            return R.error();
        }
        return R.ok();
    }
}
